package com.arvinclub.service.config;

import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import java.util.Properties;

/**
 * Configuration: 辅助bean配置
 */
@MapperScan("com/arvinclub/service/dao")
@PropertySource("classpath:database.properties")
@Configuration
@ComponentScan(basePackages = "com.arvinclub.service.service")
public class RootConfig {
    @Value("${jdbc.password}")
    private String PASSWORD;
    @Value("${jdbc.driver}")
    private String DRIVER;
    @Value("${jdbc.url}")
    private String URL;
    @Value("${jdbc.username}")
    private String USERNAME;

    /**
     * 数据源配置
     */
    @Bean
    public DriverManagerDataSource sqlDataSource() {
        final DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(DRIVER);
        dataSource.setUrl(URL);
        dataSource.setUsername(USERNAME);
        dataSource.setPassword(PASSWORD);
        return dataSource;
    }

    /**
     * pageHelper注册
     */
    @Bean
    public PageInterceptor pageHelper() {
        final PageInterceptor pageHelper = new PageInterceptor();
        final Properties p = new Properties();
        p.setProperty("offsetAsPageNum", "true");
        p.setProperty("rowBoundsWithCount", "true");
        p.setProperty("reasonable", "true");
        pageHelper.setProperties(p);
        return pageHelper;
    }

    /**
     * mapper注册
     */
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory() {
        final SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(sqlDataSource());
        sqlSessionFactory.setPlugins(new Interceptor[]{pageHelper()});
        sqlSessionFactory.setTypeAliasesPackage("com/arvinclub/model/entity");
        sqlSessionFactory.setMapperLocations(new Resource[]{new ClassPathResource("mapper/blogMapper.xml"), new ClassPathResource("mapper/userMapper.xml"), new ClassPathResource("mapper/commentMapper.xml")});
        return sqlSessionFactory;
    }

}

